//
//  AppDelegate.swift
//  YunshuApp
//
//  Created by 周文杰 on 2017/4/21.
//  Copyright © 2017年 zwj. All rights reserved.
//

import UIKit
import HandyJSON

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate,MiPushSDKDelegate, UNUserNotificationCenterDelegate {

    var window: UIWindow?
    let wechatDelegate = WechatDelegate()

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        NetworkManager.setDefaultUserAgent()
        WXApi.registerApp("wx8406bd4e9ab1be96") //改成你实际的AppID
        WeiboSDK.registerApp("3924590339")
        _=TencentOAuth.init(appId: "1105861579", andDelegate: nil)
        User.get.fromPersistence()
        
//        application.registerForRemoteNotifications()
//        application.registerUserNotificationSettings(UIUserNotificationSettings.init(types: [.badge,.sound], categories: nil))
        
        MiPushSDK.registerMiPush(self, type: UIRemoteNotificationType(rawValue: UInt(0)), connect: true);
        
//        // 点击通知打开app处理
//        let userInfo = launchOptions?[UIApplicationLaunchOptionsKey.remoteNotification]
//        if (userInfo != nil) {
//            let alertVC = UIAlertController.init(title: "消息", message: "\(userInfo)", preferredStyle: .alert)
//            let act = UIAlertAction.init(title: "确定", style: .cancel, handler: nil)
//            alertVC.addAction(act)
//            nav.present(alertVC, animated: true, completion: nil)
//            
//        }
        UIApplication.shared.applicationIconBadgeNumber = 0
        
        return true
    }
    
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
//        let nsdataStr = NSData.init(data: deviceToken)
//
//        print(nsdataStr.description)
//
//        let datastr = nsdataStr.description.replacingOccurrences(of: "<", with: "").replacingOccurrences(of: ">", with: "").replacingOccurrences(of: " ", with: "")
//        print(datastr)
        let nsdata = NSData(data: deviceToken)
        let token = nsdata.description
        print("APNS Token: \(token)")
        MiPushSDK.bindDeviceToken(deviceToken)
        
    }
    
    func miPushRequestSucc(withSelector selector: String!, data: [AnyHashable : Any]!) {
        let log = "\(selector): \(data)"
        if selector == "bindDeviceToken:" {
            let regId = data["regid"]
            print("regId = \(regId)")
            User.get._tempChannel = regId as! String
            User.updateChannelId()

        }
    }
    
    func miPushRequestErr(withSelector selector: String!, error: Int32, data: [AnyHashable : Any]!) {
        let log = "command error(\(error)|\(selector)): \(data.description)"
        print(log)
    }
    
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print(error.localizedDescription)
    }
    
    //    func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) {
    //
    //        application.registerForRemoteNotifications()
    //
    //    }
    
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
        if !User.isLogin() {
            return
        }
        if let aps = userInfo["aps"] as? NSDictionary {
            if (aps["badge"] is NSNull) {
                return
            }
            if let num = aps["badge"] as? Int {
                UIApplication.shared.applicationIconBadgeNumber = num
            }
            if let kxid = userInfo["kxid"] as? String{
                let navi = window?.rootViewController as! UINavigationController
                
                _ = NetworkManager.GET(NetworkManager.Kuaixun_Detail,params: ["id":kxid] , callback: { (isSuccess, resp) in
                    if isSuccess {
                        let model = JSONDeserializer<KuaixunModel>.deserializeFrom(dict:resp.wtmDic as NSDictionary)!
                        let url = NetworkManager.BASE_URL + NetworkManager.Kuaixun_Share + "id="+kxid
                        
                        let vc:WebViewController = UIStoryboard.init(name: "mainStoryBoard", bundle: Bundle.main).instantiateViewController(withIdentifier: WebViewController.VCID) as! WebViewController
                        vc.url = url
                        vc.shareObj = ShareObject.init()
                        vc.shareObj?.image = nil
                        vc.shareObj?.imageUrl = "http://www.yunshutech.com/pictureService/showImage.action?type=0&filename=ccbe074f-b85f-454b-bc25-b1f977046222.png"
                        vc.shareObj?.url = url + "&iscome=1"
                        
                        vc.shareObj?.title = model.title
                        vc.title = "快讯详情"
                        navi.pushViewController(vc, animated: true)

                    }
                })
                
                
            }
        }
        
    }
    

    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }
    func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
        return (WXApi.handleOpen(url as URL? , delegate: wechatDelegate)) || (TencentOAuth.handleOpen(url))
    }

}

